package com.cn.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by chenyuncong on 2019/5/9.
 */
@Configuration
public class ElasticsearchConfiguration {

    private static final String CLUSTER_NODES_SPLIT_SYMBOL = ",";
    private static final String HOST_PORT_SPLIT_SYMBOL = ":";

    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String clusterNodes;

    @Value("${spring.data.elasticsearch.cluster-name}")
    private String clusterName;

    @Bean
    public TransportClient getClient() throws UnknownHostException {
        System.out.println("---------------init es client");
        InetSocketTransportAddress node = null;

        Settings setttings = Settings.builder()
                .put("client.transport.sniff", true)
                .put("cluster.name", clusterName).build();  //集群名字

        TransportClient client = new PreBuiltTransportClient(setttings);

        String [] nodes = clusterNodes.split(CLUSTER_NODES_SPLIT_SYMBOL);
        for(String n:nodes){
            String[] array=n.split(HOST_PORT_SPLIT_SYMBOL);
            node = new InetSocketTransportAddress(InetAddress.getByName(array[0]),Integer.parseInt(array[1]));
            client.addTransportAddress(node);
        }

        return client;
    }

}
